// 过程监督弹窗
<template>
  <div class="addDialog basic-from">
    <el-dialog custom-class="small-padding-dialog" :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" @close="handleClosed" :close-on-click-modal="false">
      <div class="dialogWrap basic-from">
        <el-form ref="dialogForm" :rules="type == 'approval' ? approvalRules: rules" :model="formData" class="form-wrap">
          <h4 class="dialogItemTitle full">装修申请上报信息</h4>
          <el-form-item label="上报人" prop="initiator">
            <el-input v-halfCharCode v-model="formData.initiator" maxlength="20" :readonly="isReadonly" placeholder="请输入上报人" />
          </el-form-item>
          <el-form-item label="上报时间" prop="initiateTime">
            <el-date-picker v-model="formData.initiateTime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd" type="datetime" placeholder="请选择上报时间" :readonly="isReadonly" :picker-options="pickerOptions" />
          </el-form-item>
          <el-form-item label="物业名称" prop="roomIds" class="listFormItem" v-if="type == 'add'">
            <el-button class="add" type="primary" size="mini" @click="$refs.propertyChoose.show()" v-if="type == 'add'">选择物业</el-button>
            <el-select v-model="formData.roomIds" multiple placeholder="请选择" :disabled="isReadonly">
              <el-option v-for="item in formData.roomId" :key="item.roomId" :label="item.propertyName" :value="item.roomId"></el-option>
            </el-select>
            <!-- <el-input v-halfCharCode v-model="formData.roomId" readonly placeholder="请输入内容" /> -->
          </el-form-item>
          <el-form-item label="物业名称" class="listFormItem" v-if="type != 'add'">
            <el-input v-halfCharCode v-model="formData.propertyName" readonly placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="工程名称" prop="engineeringName">
            <el-input v-halfCharCode v-model="formData.engineeringName" :readonly="isReadonly" maxlength="100" placeholder="请输入工程名称" />
          </el-form-item>
          <el-form-item label="装修说明" class="full" prop="problemDesc">
            <el-input v-halfCharCode v-model="formData.problemDesc" type="textarea" :readonly="isReadonly" placeholder="请输入内容" maxlength="200" />
          </el-form-item>
          <el-form-item label="备注" class="full" prop="remarks">
            <el-input v-halfCharCode v-model="formData.remarks" type="textarea" :readonly="isReadonly" :placeholder="isReadonly ? '暂无内容' : '请输入内容'" maxlength="200" />
          </el-form-item>
          <!-- 附件 -->
          <div v-if="dialogVisible" class="full">
            <h4 class="dialogItemTitle">上传附件</h4>
            <v-upload ref="upload" :busId="formData.billId" modelType="decorateQuestion" @onSuccess="onSuccess" v-model="uploadFileList" isShowFileList :isView="['preview','approval'].includes(type)" :autoLoadFiles="false" />
          </div>

          <!-- 审批 -->
          <div v-if="type === 'approval'" class="full">
            <h4 class="dialogItemTitle">装修审批</h4>
            <el-form-item label="审批结果" class="full" prop="result">
              <el-radio-group v-model="formData.result">
                <el-radio label="1">同意</el-radio>
                <el-radio label="0">不同意</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审批意见" class="full" prop="approveContent">
              <el-input v-halfCharCode v-model="formData.approveContent" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </div>
          <!-- 审批查看 -->
          <el-table :data="approvalList" style="width: 100%" v-if="type === 'preview'" class="full">
            <el-table-column align="left" prop="approvePerson" label="审批人" width="160" />
            <el-table-column prop="approveTm" label="审批时间" width="160" />
            <el-table-column align="left" label="审批结果" width="160">
              <template slot-scope="scope">{{getStatusName(scope.row.approveStatus)}}</template>
            </el-table-column>
            <el-table-column align="left" prop="approveContent" label="审批意见" />
          </el-table>
        </el-form>

        <!-- 物业选择弹窗 -->
        <choose-dialog v-bind="dialogAttrs" ref="propertyChoose" @chooseData="handlePropertyChange" :disabledArr="formData.roomIds" />
      </div>
      <div slot="footer">
        <el-button @click="$bus.$emit('operationLog',formData.billId)" v-if="type==='preview'">操作日志</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button v-if="type !== 'preview'" type="primary" v-throttle="[save]">{{type == 'approval' ? '审 批':'提 交'}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment';
import { changeDecorationApply, getApproveInfo, approvalDecoration } from "@/views/wy-operate/api/decorate.js";
export default {
  name: "addDepartment",
  inject: ['initList'],
  data () {
    return {
      //弹窗类型，默认新增
      type: "add",
      //选中的物业
      radioId: "",
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        billId: "",
        // 房源信息
        roomId: [],
        // 上报人
        initiator: "",
        // 上报时间
        initiateTime: "",
        // 物业名称
        propertyName: "",
        // 工程名称
        engineeringName: "",
        // 问题描述
        problemDesc: "",
        // 备注
        remarks: "",
        // 物业类型
        propertyType: '',
        // 平台	 10 苹果 11 安卓 13 其他
        mobileDevice: '13',
        // 选择房源id
        roomIds: []
      },
      // 审批表单
      approvalForm: {
        // 审批结果
        result: "",
        // 审批内容
        approveContent: "",
        // 审批人
        approvePerson: "",
        // 审批时间
        approveTm: "",
      },
      // 审批记录
      approvalList: [],
      // 校验规则
      rules: {
        initiator: [{ required: true, message: "上报人不能为空", trigger: "blur" }],
        initiateTime: [{ required: true, message: "上报时间不能为空", trigger: "blur" }],
        roomIds: [{ required: true, message: "物业名称不能为空", trigger: "blur" }],
        engineeringName: [{ required: true, message: "工程名称不能为空", trigger: "blur" },
        { min: 1, max: 100, message: '长度在 1 到 25 个字符', trigger: 'blur' }],
      },
      // 审批校验
      approvalRules: {
        result: [{ required: true, message: "审批结果不能为空", trigger: "blur" }],
        approveContent: [{ required: true, message: "审批意见不能为空", trigger: "blur" },
        { min: 1, max: 64, message: '长度在 1 到 64 个字符', trigger: 'blur' }],
      },
      // 上传文件列表
      uploadFileList: [],

      pickerOptions: {
        disabledDate: function disabledDate (time) {
          //return time.getTime() < Date.now() // 选当前时间之后的时间
          return time.getTime() > Date.now() // 选当前时间之前的时间
        }
      }
    };
  },
  computed: {
    // 弹窗标题计算
    dialogTitle () {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增",
        approval: "审批",
      }[this.type];
    },
    // 物业选择弹窗
    dialogAttrs () {
      return {
        title: '选择物业',
        url: '/admin/user/getAllUser',
        searchKey: 'realName',
        showData: [
          { label: '物业名称', prop: 'propertyName', width: '600px', 'show-overflow-tooltip': true },
          { label: '建筑面积', prop: 'buildingArea', width: '100px' },
        ],
        returnData: ['propertyName', 'roomId'],
        primaryKey: 'roomId',
        multiple: true,
        reserveSelection: true
      }
    },
    // 判断是否只读
    isReadonly () {
      return ["preview", "approval"].includes(this.type);
    },
  },
  watch: {
    'formData.roomIds': {
      deep: true,
      handler (val) {
        if (this.formData.roomId.length) {
          this.formData.roomId = this.formData.roomId.filter(i => val.includes(i.roomId))
        }
      }
    }
  },
  methods: {
    //开启弹窗
    show ({ type, data = {} }) {
      if (['preview', 'edit', 'approval'].includes(type)) {
        this.formData = type === 'approval' ? { ...this.formData, ...this.approvalForm, ...data } : { ...this.formData, ...data };
        this.$nextTick(() => {
          this.$refs.upload && this.$refs.upload.getFiles(data.billId)
        })
        // 预览状态下获取审批结果信息
        data.billStatus && this.getStatus(data.billId)
      }
      this.type = type;
      this.dialogVisible = true;
    },
    // 获取审批相关信息
    getStatus (billId) {
      getApproveInfo(billId).then(res => {
        const { records } = res.data.data
        if (records.length) {
          this.approvalForm = {
            ...records[0],
            result: this.formData.billStatus == 11 ? '1' : '0'
          }
          this.approvalList = records
        }
      })
    },
    // 提交新增审批
    save () {
      if (this.type === 'approval') {
        this.$refs.dialogForm.validate((valid) => {
          if (valid) {
            let { result, approveContent, approvePerson } = this.formData;
            let params = {
              approveContent,
              approvePerson,
              approveTm: moment().format('YYYY-MM-DD hh:mm:ss'),
              billId: this.formData.billId,
            }

            approvalDecoration(params, result).then((res) => {
              if (res.data.code == 0) {
                this.$message.success(`${this.dialogTitle}成功!`);
                this.initList({ current: 1, keyword: '' });
                this.dialogVisible = false;
              } else {
                this.$message.error(res.data.msg)
              }
            });
          }
        })
      }

      if (['edit', 'add'].includes(this.type)) {
        this.$refs.dialogForm.validate((valid) => {
          if (valid) {
            if (this.uploadFileList.length) {
              this.$refs.upload.submit('decorateQuestion', this.formData.billId);
            } else {
              changeDecorationApply(this.formData, this.type).then(res => {
                if (res.data.code == 0) {
                  this.$message.success(`${this.dialogTitle}成功!`);
                  this.initList({ current: 1, keyword: '' });
                  this.dialogVisible = false;
                } else {
                  this.$message.error(res.data.msg)
                }
              })
            }
          }
        });
      }
    },
    // 上传成功
    async onSuccess (response, file, fileList) {
      let params = this.type == 'add' ? { ...this.formData, billId: response.data } : this.formData
      const res = await changeDecorationApply(params, this.type)
      if (res.data.code == 0) {
        this.$message.success(`${this.dialogTitle}成功!`);
        this.initList({ current: 1, keyword: '' });
        this.dialogVisible = false;
      } else {
        this.$message.error(res.data.msg)
      }
    },
    // 监听物业改变
    handlePropertyChange (data) {
      let list = this.formData.roomId.length ? this.formData.roomId.concat(data) : data
      console.log(list.length)
      this.formData = {
        ...this.formData,
        roomId: list,
        roomIds: list.map(_ => _.roomId)
        // address: data.address,
        // propertyName: data.propertyName,
        // roomId: data.roomId,
        // propertyType: data.propertyType
      };
      if (this.formData.engineeringName == "") {
        if (list.length == 1) {
          this.formData.engineeringName = list[0].propertyName + "的装修申请"
        } else {
          this.formData.engineeringName = list[0].propertyName + "等物业的装修申请"
        }
      }

    },
    // 获取审批状态名称
    getStatusName (status = this.formData.billId) {
      return {
        '10': '待审核',
        '11': '待审核',
        '12': '审核通过',
        '13': '待验收',
        '14': '验收通过',
        '15': '验收未通过'
      }[status] || ''
    },
    // 弹窗关闭还原
    handleClosed () {
      this.uploadFileList = []
      for (var i in this.formData) {
        this.formData[i] = Object.prototype.toString.call(this.formData[i]) === '[object Array]' ? [] : ''
      }
      for (var i in this.approvalForm) {
        this.approvalForm[i] = Object.prototype.toString.call(this.approvalForm[i]) === '[object Array]' ? [] : ''
      }
      this.approvalList = []
    }
  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.addDialog {
  /deep/ .el-date-editor--datetime {
    width: 100%;
  }
  .album {
    .el-col {
      margin-bottom: 20px;
    }
    .img {
      width: 100%;
      height: 200px;
    }
  }
}
</style>
